#-------------------------------------------------------------------------------
#   Trakt To Couch Potato
#   http://ttcp.codeplex.com
#
#   Grabs your movie watchlist from trakt.tv, adds them to Couch Potato
#   and removes them from your watchlist
#-------------------------------------------------------------------------------

import trakt
import mechanize

#-------------------------------------------------------------------------------
# User Specific Config
traktApiKey = "" # Available from http://trakt.tv/api-docs/authentication
traktUsername = "username"
traktPassword = "password"

couchPotatoBaseURL = "http://localhost:5000"
couchPotatoUsername = "username"
couchPotatoPassword = "password"

#-------------------------------------------------------------------------------
# String Constants
couchPotatoURL = couchPotatoBaseURL + "/movie/imdbAdd/"
couchPotatoParamId = "?id="
couchPotatoParamYear = "&year="

#-------------------------------------------------------------------------------
def addToCouchPotato(imdb_id, year):
    url = couchPotatoURL + couchPotatoParamId + imdb_id + couchPotatoParamYear + str(year);
    br = mechanize.Browser()
    
    # ignore robots setting and scrape anyway
    br.set_handle_robots(False)

    # Couch Potato login info 
    br.add_password(url, couchPotatoUsername, couchPotatoPassword)
    
    # Open the add movie page
    response1 = br.open(url)
    assert br.viewing_html()
    
    # Get the form
    forms = mechanize.ParseResponse(response1, backwards_compat=False)
    form = forms[0]
    
    # Submit it
    br.open( form.click() )
    

#-------------------------------------------------------------------------------
def main():
    # Get the current watch list
    movies = trakt.movieWatchlist(traktUsername, traktPassword, traktApiKey)
    for movie in movies:
        # add the movie to couch potato
        addToCouchPotato(movie["imdb_id"], movie["year"])
        print "Added", movie["title"], "to Couch Potato"
        # remove it from the watch list
        trakt.removeMovieFromWatchlist(traktUsername, traktPassword, traktApiKey, movie["title"], movie["year"], movie["imdb_id"])
        print "Removed", movie["title"], "from trakt.tv watchlist"    
        
#-------------------------------------------------------------------------------
main()
